<template>
  <div class="virtualTerminalItem_container m-t-20px" v-if="!refresh">
    <div class="m-b-10px">
      <div class="global_btn" @click="handleRefresh">刷新当前终端</div>
    </div>
    <div v-if="loading" class="loading-mask">
      <div class="loading-spinner">
        <svg class="circular" viewBox="25 25 50 50">
          <circle class="path" cx="50" cy="50" r="20" fill="none"/>
        </svg>
        <p class="loading-text">正在加载终端...</p>
      </div>
    </div>
    <div class="iframe_wrapper">
      <iframe 
        v-if="!isError"
        :src="iframeUrl" 
        :key="iframeKey"      
        ref="iframeRef"
        @load="handleIframeLoad"
        @error="handleIframeError"
        style="border: none;"
      />
      <div class="bottom-spacer"></div>
      <el-empty v-if="isError" description="URL不可用" />
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue'
export default defineComponent({
 name: 'VirtualTerminalItem',
})
</script>
<script setup lang="ts">
const refresh = ref(false)
const isError = ref(false)
const loading = ref(true)
const iframeKey = ref(0)
const hasBeenActivated = ref(false)
const iframeRef = ref<HTMLIFrameElement | null>(null)
const iframeHeight = ref('800px') // 默认高度

const props = defineProps<{
  ip: string,
  port: number,
  isActive?: boolean
}>()

const iframeUrl = computed(() => {
  return `http://${props.ip}:${props.port}`
})

// 计算并设置iframe高度
function calculateIframeHeight() {
try {
  const iframe = iframeRef.value
  if (!iframe) return
  // 尝试获取内容高度（可能受跨域限制）
  try {
    if (iframe.contentWindow && iframe.contentWindow.document.body) {
      // 获取内容实际高度 + 额外的底部空间
      const contentHeight = iframe.contentWindow.document.body.scrollHeight
      if (contentHeight > 0) {
        iframeHeight.value = `${contentHeight + 80}px`
        iframe.style.height = iframeHeight.value
        return
      }
    }
  } catch (e) {
    console.log('跨域限制，无法直接获取iframe内容高度')
  }  
  // 备用解决方案：设置一个足够大的高度
  iframeHeight.value = '1000px'
  iframe.style.height = iframeHeight.value
} catch (e) {
  console.error('调整iframe高度失败', e)
}
}

function handleIframeLoad() {
loading.value = false
isError.value = false
// 延迟计算高度，确保内容已加载完成
setTimeout(calculateIframeHeight, 500)
}

function handleIframeError() {
loading.value = false
isError.value = true
}

watch(() => props.isActive, (newValue) => {
if (newValue === true) {
  if (!hasBeenActivated.value) {
    console.log("组件变为活动状态")
    hasBeenActivated.value = true
    setTimeout(() => {
      iframeKey.value += 1
    }, 50)
  } else {
    // 即使不是第一次激活，也重新计算高度
    setTimeout(calculateIframeHeight, 300)
  }
}
}, { immediate: true })

function handleRefresh() {
refresh.value = true
nextTick(() => {
  refresh.value = false
  // 刷新后重新计算高度
  setTimeout(calculateIframeHeight, 500)
})
}

// 窗口大小变化时重新计算
function handleResize() {
if (props.isActive) {
  calculateIframeHeight()
}
}

onMounted(() => {
loading.value = true
window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
window.removeEventListener('resize', handleResize)
})
</script>

<style lang="scss" scoped>
.virtualTerminalItem_container {
position: relative;
display: flex;
flex-direction: column;
height: auto;
min-height: 400px;
overflow: visible;
}

.iframe_wrapper {
position: relative;
width: 100%;
height: auto;
overflow: visible; 
border: 1px solid rgba(28, 55, 96, 0.5);
border-radius: 4px;
background-color: rgba(1, 14, 36, 0.3);
padding-bottom: 20px;
}

iframe {
display: block;
width: 100%;
min-height: 800px;
height: v-bind(iframeHeight);
overflow: visible;
}

.bottom-spacer {
height: 30px; /* 底部间距 */
width: 100%;
}

.loading-mask {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #010e24;
display: flex;
justify-content: center;
align-items: center;
z-index: 1000;
}

.loading-spinner {
text-align: center;
}

.loading-text {
color: #409eff;
margin-top: 10px;
font-size: 14px;
}

.path {
stroke-dasharray: 90, 150;
stroke-dashoffset: 0;
stroke-width: 2;
stroke: #409eff;
stroke-linecap: round;
animation: loading-dash 1.5s ease-in-out infinite;
}

@keyframes loading-rotate {
100% {
  transform: rotate(360deg);
}
}

@keyframes loading-dash {
0% {
  stroke-dasharray: 1, 200;
  stroke-dashoffset: 0;
}
50% {
  stroke-dasharray: 90, 150;
  stroke-dashoffset: -40px;
}
100% {
  stroke-dasharray: 90, 150;
  stroke-dashoffset: -120px;
}
}

.circular {
width: 42px;
height: 42px;
animation: loading-rotate 2s linear infinite;
}
</style>